import json

from django.utils.decorators import method_decorator

from gis.common.django_ext.decorators import validate_parameters
from gis.common.django_ext.views import BaseView
from gis.common.exceptions import BizException
from itpay.core.agency import receipt_service, agency_service
from itpay.core.agency.const import BankCode
from itpay.core.agency.errors import ERROR_RECEIPT_ADDRESS_NOT_EXISTS, ERROR_AGENT_DISABLE, ERROR_AGENCY_NOT_WORKING
from itpay.core.recharge_order import order_service
from . import open_form

BANK_NAME_MAP = {
    BankCode.CCB: '中国建设银行'
}


def auth_token(token):
    """
    使用对称加密算法。
    主要检验过期时间字段
    """
    pass


class ReceiptAddressDetailView(BaseView):
    @method_decorator(validate_parameters(open_form.ReceiptAddressDetailSchema))
    def get(self, request, receipt_id, cleaned_data):
        # auth_token(cleaned_data['token'])
        receipt = receipt_service.get_receipt_address(receipt_id)
        agency = agency_service.get_agency_by_id(receipt['agency_id'])
        tips = None
        if not receipt['status']:
            tips = "该收款账号已被禁用，请获取新的收款账号！"
        elif not agency['enable']:
            tips = "当前代理被禁用，请选择其他代理充值"
        elif not agency['working']:
            tips = '代理当前不在线，若要充值请联系其他代理！'

        return {
            'id': receipt['id'],
            'receipt_type': receipt['receipt_type'],
            'receipt_method': receipt['receipt_method'],
            'account': receipt['account'],
            'qr_code': receipt['qr_code'],
            'account_qr_code': receipt['account_qr_code'],
            'huabei_fee_rate': receipt['huabei_fee_rate'],
            'credit_fee_rate': receipt['credit_fee_rate'],
            'first_name': receipt['first_name'],
            'last_name': receipt['last_name'],
            'bank_code': receipt['bank_code'],
            'bank_branch': receipt['bank_branch'],
            'mch_name': receipt['mch_name'],
            'ali_zkl': receipt['ali_zkl'],
            'tips': tips
        }


class RechargeOrderDetailView(BaseView):
    @method_decorator(validate_parameters(open_form.RechargeOrderDetailSchema))
    def get(self, request, order_id, cleaned_data):
        # auth_token(cleaned_data['token'])
        order = order_service.get_order(order_id)
        receipt = json.loads(order['receipt_ext'])

        return {
            'id': order['id'],
            'pay_type': order['pay_type'],
            'amount': order['amount'],
            'real_amount': order['real_amount'],
            'recharge_amount': order['recharge_amount'],
            'created_at': order['created_at'],
            'status': order['status'],
            'account': receipt['account'],
            'first_name': receipt['first_name'],
            'last_name': receipt['last_name'],
            'bank_code': receipt['bank_code'],
            'bank_branch': receipt['bank_branch'],
        }
